package com.mastercard.labs
import grails.converters.JSON
import org.apache.shiro.SecurityUtils

import java.text.SimpleDateFormat

class ReportController {
	def cardService, transactionService, categoryService, transactionCategoryService, dealService, userService, merchantService, voucherService
	
    def index() {
		// Get cards
		//def user = User.findByEmail("zifeng@gmail.com")
		def user = SecurityUtils.subject.session.getAttribute("current_user")
		def cardIds = params.card_id
		def cards = new ArrayList()
		if (cardIds == null) {
			cards = cardService.getCards(user)
			cardIds = new ArrayList()
		}
		else {
			if (cardIds instanceof String) {
				cardIds = [cardIds]
			}
			
			for (String cardId in cardIds) {
				def cardIdLong = Long.parseLong(cardId)
				def card = Card.get(cardIdLong)
				cards.add(card)
			}
		}
		
		def endStr = params.get("to_date")
		def startStr = params.get("from_date")
		Date fromDate
		def formatter = new SimpleDateFormat("dd-MM-yyyy")
		if (startStr != null) {
			fromDate = formatter.parse(startStr);
		} else {
			Calendar cal = Calendar.getInstance()
			cal.add(Calendar.MONTH, -5)
			fromDate = cal.getTime()
		}

		Date toDate
		if (endStr != null) {
			toDate = formatter.parse(endStr);
		} else {
			toDate = new Date()
		}

		def transactions = transactionService.getTransactionsOfCards(cards, fromDate, toDate)
		def monthlySpending = transactionService.getTotalSpendingOfCards(cards, fromDate, toDate)

		render (view: 'report', model:[
					cardsJSON:new JSON(cards).toString(),
					cards: cards,
					cardSet: Arrays.asList(cardIds),
					allCards: cardService.getCards(user),
					transactions: transactions,
					categorySpendingForCards: new JSON(transactionService.getCategorySpendingForCards(cards, fromDate, toDate)),
					dateFormat: formatter,
					monthlySpending: new JSON(monthlySpending),
					categories: categoryService.getAll(),
					transactionCategoryService: transactionCategoryService,
					deals: dealService.getDeals(user),
					categorySpending: new JSON(transactionService.getCategorySpendingOfTxns(transactions)),
					fromDate: fromDate,
					toDate: toDate])
	}
}
